#include <pthread.h>
#include <functional>
#include <iostream>
#include <cstdio>
#include <cstring>

namespace threadspace
{
    static uint32_t number = 1;

    template <typename T>
    class Thread
    {
    using func_t = std::function<void(T)>;

    private:
        void enableDetach()
        {
            std::cout << "线程被分离" << std::endl;
            _isdetach = true;
        }
        void enableRunning()
        {
            _isrunning = true;
        }

        static void *routine(void *args)
        {
            Thread<T> *const self = static_cast<Thread<T> *const>(args);
            self->enableRunning(); // 设置标记位为运行状态
            if (self->_isdetach)
                self->Detach();
            self->_func(self->_data);

            return nullptr;
        }

    public:
        Thread(func_t func, T data)
            : _tid(0), _res(nullptr), _isdetach(false), _isrunning(false), _func(func), _data(data)
        {
            _name = "thread-" + std::to_string(number);
        }
        void Detach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            enableDetach();
        }
        bool Start()
        {
            if (_isrunning)
            {
                std::cout << "这个线程存在, 不能申请了" << std::endl;
                return false;
            }
            int n = pthread_create(&_tid, nullptr, routine, this);
            if (n != 0)
            {
                std::cerr << "线程创建失败 : " << std::strerror(n) << std::endl;
                return false;
            }

            std::cout << "线程创建成功" << std::endl;
            return true;
        }
        bool Stop()
        {
            if (!_isrunning)
            {
                std::cout << "线程没有运行, 无法取消" << std::endl;
                return false;
            }
            int n = pthread_cancel(_tid);
            if (n != 0)
            {
                std::cerr << "线程取消失败 : " << std::strerror(n) << std::endl;
                return false;
            }
            std::cout << "线程已经被取消" << std::endl;
            return true;
        }
        bool Join()
        {
            if (_isdetach)
            {
                std::cout << "这个线程是分离状态, 不用等待" << std::endl;
                return false;
            }
            int n = pthread_join(_tid, nullptr);
            if (n != 0)
            {
                std::cerr << "线程等待失败 : " << std::strerror(n) << std::endl;
                return false;
            }
            std::cout << "线程等待成功" << std::endl;
            return true;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        void *_res;
        bool _isdetach;
        bool _isrunning;
        func_t _func;
        T _data;
    };
};